package com.kchouse.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.kchouse.MainActivity;
import com.kchouse.common.API;
import com.kchouse.common.BaseApp;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.ToastUtils;
import com.kchouse.homepage.BuyOrderActivity;
import com.kchouse.homepage.BuyPrestoreOrderActivity;
import com.kchouse.homepage.DepositDetailsActivity;
import com.kchouse.homepage.PayResultsActivity;
import com.kchouse.mine.LoginPhoneActivity;
import com.kchouse.mine.OrderActivity;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

    private IWXAPI api;
    private WXPayEntryActivity mContent;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        BaseApp.msgApi.handleIntent(getIntent(), this);

        mContent = this;
        api = WXAPIFactory.createWXAPI(this, BaseApp.APP_WeChatID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        BaseApp.msgApi.handleIntent(intent, this);
    }

    @Override
    public void onResp(BaseResp baseResp) {
        if (baseResp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            BaseApp.setResp(baseResp);
            Log.e("errCode", baseResp.errCode+"");
            switch (baseResp.errCode) {
                case 0:
                    Intent intent = new Intent();
                    if (!TextUtils.isEmpty(BuyOrderActivity.orderNo)) {
                        intent.putExtra("Order","1");//套餐订单
                    }
                    if (!TextUtils.isEmpty(BuyPrestoreOrderActivity.orderNo)) {
                        intent.putExtra("Order","2");//预存订单
                    }
                    if (!TextUtils.isEmpty(DepositDetailsActivity.orderNo)) {
                        intent.putExtra("Order","3");//定金订单
                    }
                    intent.setClass(mContent, PayResultsActivity.class);
                    startActivity(intent);
                    ToastUtils.getInstanc(this).showToast("支付成功");
                    BuyOrderActivity.orderNo="";
                    BuyPrestoreOrderActivity.orderNo="";
                    DepositDetailsActivity.orderNo="";
                    break;
                case -1:
                    Log.e("WeChat", "onResp: -1");
//                    ToastUtils.getInstanc(this).showToast("onResp: -1");
                    ToastUtils.getInstanc(this).showToast("未知错误请联系管理员");
                    break;
                case -2:
                    Log.e("WeChat", "onResp: -2");
//                    ToastUtils.getInstanc(this).showToast("onResp: -2");
                    ToastUtils.getInstanc(this).showToast("支付失败，请重新支付");

                    if (!TextUtils.isEmpty(BuyOrderActivity.orderNo)) {
                        PostCancelOrder();
                    }
                    if (!TextUtils.isEmpty(BuyPrestoreOrderActivity.orderNo)) {
                        PostCancelOrder();
                    }
                    break;
            }

        }
        finish();
    }

    /**
     * 取消订单
     */
    private void PostCancelOrder() {
        String url = API.PostCancelOrder + BuyPrestoreOrderActivity.orderNo;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("orderId", BuyPrestoreOrderActivity.orderNo);


        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
//                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
//                    String datastr = json.getString("data");
//                    JSONObject data = JSONObject.parseObject(datastr);
//                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
//                dismissdialog();
            }

        });
    }
}
